package controller;

import helpers.Paginator;
import helpers.SolrHelper;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import debug.RealEstateDebug;

import model.Paginate;
import model.RealEstate;
import model.SearchParam;
import model.SearchResult;

/**
 * Servlet implementation class Result
 */
public class Result extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String key = request.getParameter("key");
		String strPage = request.getParameter("page");
		int page = 1;
		
		SearchParam searchParam = new SearchParam();
		Paginator paginator = new Paginator();
		
		
		//Check empty
		if (!key.isEmpty()) searchParam.setKey(key);
		if (strPage != null && !strPage.isEmpty()) { 
			page = Integer.parseInt(strPage);
		}
		searchParam.setPage(page);
		
		SearchResult sr = (SearchResult) SolrHelper.search(searchParam);
		
		paginator.setLimit(searchParam.getLimit());
		Paginate paginate = paginator.paginate(page, sr.getTotalResult());
		
		request.setAttribute("searchResult", sr);
		request.setAttribute("key", key);
		request.setAttribute("paginate", paginate);
		try {
			request.getRequestDispatcher("/pages/search_result.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
